//
//  SEGSliderView.m
//  Tab分页策划测试
//
//  Created by 刘山 on 16/10/1.
//  Copyright © 2016年 刘山. All rights reserved.
//
#import "SEGSliderView.h"

#import <Masonry/Masonry.h>

#if __has_include(<Commom/SEGLayoutMacro.h>)
#import <Commom/SEGLayoutMacro.h>
#else
#import "SEGLayoutMacro.h"
#endif

#if __has_include(<Commom/SEGColorManager.h>)
#import <Commom/SEGColorManager.h>
#else
#import "SEGColorManager.h"
#endif

#import "SEGPlatformManager.h"

@implementation SEGSliderTitleViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self == [super initWithFrame:frame]) {
        self.backgroundColor = kColor_L2;
        [self.contentView addSubview:self.titleBtn];
    }
    return self;
}

- (UIButton*)titleBtn
{
    if (!_titleBtn) {
        _titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_titleBtn setFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height - 0.5)];
        _titleBtn.center = self.contentView.center;
        _titleBtn.userInteractionEnabled = NO;
        [_titleBtn setTitleColor:kColor_1 forState:UIControlStateNormal];
        [_titleBtn setBackgroundColor:kColor_W];
    }
    return _titleBtn;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.titleBtn setFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height - 0.5)];
}

@end

@implementation SEGSliderContentViewCell
- (void)setRootViewController:(UIViewController*)rootViewController
{
    _rootViewController = rootViewController;

    for (UIView* V in self.contentView.subviews) {
        [V removeFromSuperview];
    }

    [self.contentView addSubview:self.rootViewController.view];
    [self.rootViewController.view setFrame:self.contentView.frame];
    //[self.rootViewController.view setFrame:CGRectMake(0, 0, self.superContentSize.width, self.superContentSize.height )];
}
@end

@interface SEGSliderView () <UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate>

@end

@implementation SEGSliderView{
    BOOL isindexExist;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self == [super initWithFrame:frame]) {
        [self addSubview:self.titleCollectionView];
        [self addSubview:self.titleLineView];
        [self addSubview:self.contentCollectionView];

        self.contentCollectionView.delegate = self;
        self.contentCollectionView.dataSource = self;

        self.titleCollectionView.dataSource = self;
        self.titleCollectionView.delegate = self;

        [self.titleCollectionView addSubview:self.lineView];

        self.startIndex = 0;
        
        isindexExist = NO;

        [self addSubview:self.backBtn];
    }
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
}

- (void)setDataSource:(NSArray<UIViewController*>*)dataSource
{
    _dataSource = dataSource;

    [self.titleCollectionView reloadData];

    [self.contentCollectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

#pragma mark - 以下是上下联动的方法
//下面这个方法是点击标题按钮，同步下面的内容界面
- (void)collectionView:(UICollectionView*)collectionView didSelectItemAtIndexPath:(NSIndexPath*)indexPath
{
    if (collectionView.tag == 1001) {
        if (self.titledelegate && [self.titledelegate respondsToSelector:@selector(SliderTitleClickWithIndexPath:)]) {
            [self.titledelegate SliderTitleClickWithIndexPath:indexPath];
        }
        // 解决从个人资料返回散退的BUG。
        if (self.dataSource.count < indexPath.row) {
            return;
        }
        
        [self.contentCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        [self setlineViewFrameWithIndexPath:indexPath];
    }

    self.currentIndex = indexPath.row;
    if (self.delegate && [self.delegate respondsToSelector:@selector(sliderView_Seleted:)]) {
        [self.delegate sliderView_Seleted:indexPath.row];
    }
}

- (void)scrollViewWillEndDragging:(UIScrollView*)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint*)targetContentOffset
{
    if (scrollView.tag == 1002) {

        CGPoint p = *targetContentOffset;

        NSInteger row = p.x / CGRectGetWidth(self.contentCollectionView.frame);

        self.currentIndex = row;
        [self.delegate sliderView_Seleted:row];

        NSIndexPath* indexPath = [NSIndexPath indexPathForItem:row inSection:0];

        NSInteger headItem = 0;
        if (velocity.x >= 0) { //右侧滑
            headItem = (row + 1) >= self.dataSource.count ? row : (row + 1);
        }
        else { //左侧滑
            headItem = (row - 1) < 0 ? 0 : (row - 1);
        }

        //这句解决下滑快消失的BUG
        [self.titleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:headItem inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.titleCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            [self setlineViewFrameWithIndexPath:indexPath];
        });
    }
}

- (void)setlineViewFrameWithIndexPath:(NSIndexPath*)indexPath
{
    SEGSliderTitleViewCell* cell = (SEGSliderTitleViewCell*)[self.titleCollectionView cellForItemAtIndexPath:indexPath];
    [self.lineView setFrame:CGRectMake(CGRectGetMinX(cell.frame) + CGRectGetMinX(cell.titleBtn.titleLabel.frame) - 6, CGRectGetHeight(cell.frame) - 2.5 - 3, CGRectGetWidth(cell.titleBtn.titleLabel.frame) + 12, 2.5)];
    [cell.titleBtn.titleLabel setTextColor:kColor_1];
    self.currentIndexPath = indexPath;
}

#pragma mark - 以上是上下联动的方法

- (UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath
{
    
    isindexExist = YES;
    
    if (collectionView.tag == 1001) {
        SEGSliderTitleViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:SEGSliderViewTitleIdentifier forIndexPath:indexPath];

        NSString* contentStr = self.dataSource[indexPath.row].title;
        [cell.titleBtn setTitle:contentStr forState:UIControlStateNormal];
        cell.titleBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        cell.titleBtn.tag = indexPath.row;
        return cell;
    }

    if (collectionView.tag == 1002) {
        SEGSliderContentViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:SEGSliderViewContentIdentifier forIndexPath:indexPath];
        cell.superContentSize = collectionView.frame.size;
        cell.rootViewController = self.dataSource[indexPath.row];
        return cell;
    }

    return nil;
}

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath
{

    if (collectionView.tag == 1001) {

        //return CGSizeMake(self.titleCollectionView.bounds.size.width / self.showCount, self.titleCollectionView.bounds.size.height);

        /*========以下是解决title标题内容很长时候现实全部内容========*/
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIViewController* VC = self.dataSource[indexPath.row];
        CGFloat nomalMaigin = self.titleCollectionView.bounds.size.width / self.showCount;

        NSDictionary* attribute = @{ NSFontAttributeName : btn.titleLabel.font };

        CGSize textSize = [VC.title boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.titleCollectionView.bounds), 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;

        CGFloat titleWidth = textSize.width > nomalMaigin ? textSize.width : nomalMaigin;

        return CGSizeMake(titleWidth, self.titleCollectionView.bounds.size.height);
    }

    if (collectionView.tag == 1002) {

        return self.contentCollectionView.bounds.size;
    }

    return CGSizeZero;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    [self.backBtn setBackgroundColor:kColor_W];

    if (self.showBackBtn) {
        [self.titleCollectionView setFrame:CGRectMake(40, 0, self.bounds.size.width - 40, 40)];
    }
    else {
        [self.titleCollectionView setFrame:CGRectMake(0, 0, self.bounds.size.width, 40)];
    }

    [self.titleLineView setFrame:CGRectMake(0, CGRectGetHeight(self.titleCollectionView.frame) - 0.5, CGRectGetWidth(self.contentCollectionView.frame), 0.5)];

    [self.contentCollectionView setFrame:CGRectMake(0, 40, self.bounds.size.width, self.bounds.size.height - 40)];

    [self.backBtn setFrame:CGRectMake(0, CGRectGetHeight(self.titleCollectionView.frame) - 0.5 - 40, 40, 40)];

    [self.contentCollectionView reloadData];
     [self.titleCollectionView reloadData];
}

- (UICollectionView*)titleCollectionView
{
    if (!_titleCollectionView) {
        _titleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.titleLayout];
        [_titleCollectionView registerClass:[SEGSliderTitleViewCell class] forCellWithReuseIdentifier:SEGSliderViewTitleIdentifier];
        _titleCollectionView.tag = 1001;
        _titleCollectionView.showsHorizontalScrollIndicator = NO;
        _titleCollectionView.bounces = NO;
        _titleCollectionView.backgroundColor = kColor_W;
        //_titleCollectionView.layer.borderWidth = 0.5;
        //_titleCollectionView.layer.borderColor = kColor_S1.CGColor;
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
            _titleCollectionView.prefetchingEnabled = NO;
        }
    }
    return _titleCollectionView;
}

- (UICollectionView*)contentCollectionView
{
    if (!_contentCollectionView) {
        _contentCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.contentLayout];
        [_contentCollectionView registerClass:[SEGSliderContentViewCell class] forCellWithReuseIdentifier:SEGSliderViewContentIdentifier];
        _contentCollectionView.showsHorizontalScrollIndicator = NO;
        _contentCollectionView.tag = 1002;
        _contentCollectionView.bounces = NO;
        _contentCollectionView.backgroundColor = kColor_W;
        _contentCollectionView.pagingEnabled = YES;
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
            _titleCollectionView.prefetchingEnabled = NO;
        }
    }
    return _contentCollectionView;
}

- (UICollectionViewFlowLayout*)titleLayout
{
    if (!_titleLayout) {
        _titleLayout = [[UICollectionViewFlowLayout alloc] init];
        _titleLayout.minimumLineSpacing = 0;
        _titleLayout.minimumInteritemSpacing = 0;
        _titleLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _titleLayout;
}

- (UICollectionViewFlowLayout*)contentLayout
{
    if (!_contentLayout) {
        _contentLayout = [[UICollectionViewFlowLayout alloc] init];
        _contentLayout.minimumLineSpacing = 0;
        _contentLayout.minimumInteritemSpacing = 0;
        _contentLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _contentLayout;
}

- (NSIndexPath*)oldIndexPath
{
    if (!_oldIndexPath) {
        _oldIndexPath = [[NSIndexPath alloc] init];
    }
    return _oldIndexPath;
}

- (UIView*)lineView
{
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = kColor_1;
    }
    return _lineView;
}
- (UIView*)titleLineView
{
    if (!_titleLineView) {
        _titleLineView = [[UIView alloc] init];
        _titleLineView.backgroundColor = kColor_L2;
    }
    return _titleLineView;
}
- (UIButton*)backBtn
{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setHidden:YES];
        [_backBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_back")] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

- (void)backBtnClick
{
    [self.delegate sliderView_back];
}

- (void)setStartIndex:(NSInteger)startIndex
{
    _startIndex = startIndex;

    [self timer];
}
- (NSTimer*)timer
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(moveThePage) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    return _timer;
}

- (void)moveThePage
{
    if ([self.titleCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.startIndex inSection:0]]) {

        [self collectionView:self.titleCollectionView didSelectItemAtIndexPath:[NSIndexPath indexPathForItem:self.startIndex inSection:0]];
        [self timeClose];
    }
    
    if (isindexExist) {
    [self.titleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.startIndex inSection:0] atScrollPosition:0 animated:NO];
    }
    
}

-(void)setPageWithIndex:(NSInteger)index{
    self.startIndex = index;
    [self collectionView:self.titleCollectionView didSelectItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    [self timeClose];
}

-(void)timeClose{
            [self.timer invalidate];
            self.timer = nil;
}

- (NSIndexPath*)currentIndexPath
{
    if (!_currentIndexPath) {
        _currentIndexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    }
    return _currentIndexPath;
}

- (void)setShowBackBtn:(BOOL)showBackBtn
{
    _showBackBtn = showBackBtn;
    [self timer];
    [self.backBtn setHidden:!_showBackBtn];
    [self layoutSubviews];
    [self.titleCollectionView reloadData];

    self.startIndex = self.currentIndexPath.row;
 
}



- (NSInteger)showCount
{
    if (!_showCount) {
        _showCount = 6;
    }
    return _showCount;
}

- (void)setIsCloseContentScroll:(BOOL)isCloseContentScroll
{
    _isCloseContentScroll = isCloseContentScroll;
    [self.contentCollectionView setScrollEnabled:!_isCloseContentScroll];
}
@end
